<?php

namespace App\Http\Controllers\Recommend;

use App\Http\Controllers\Controller;
use App\Http\Requests\Recommend\Reclist0Request;
use App\Models\Application\CollistData;
use App\Models\Application\ColumnAsset;
use App\Models\Application\Muticolumn;
use App\Models\Application\Pagetpl;
use App\Models\Application\Paneltpl;
use App\Models\Entity\Asset\Video\Vasseti;
use App\Models\Recommend\Reccat;
use App\Models\Recommend\Reclist0;
use App\Models\Recommend\Reclist0Data;
use App\Repositories\Recommend\Reclist0Repository;
use DB;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Response;

class Reclist0Controller extends Controller
{
    use ModelForm;

    /** @var  Reclist0Repository */
    private $reclist0Repository;

    public function __construct(Reclist0Repository $reclist0Repo)
    {
        $this->reclist0Repository = $reclist0Repo;
    }

    /**
     * Display a listing of the Reclist0.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('recommend.reclist0s.index_header'));
            $content->description(__('recommend.reclist0s.index_description'));

            $content->body($this->grid());
            $content->row(view('recommend.reclist0s.index'));

        });
    }

    /**
     * Show the form for creating a new Reclist0.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('recommend.reclist0s.create_header'));
            $content->description(__('recommend.reclist0s.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Reclist0 in storage.
     *
     * @param Reclist0Request $request
     *
     * @return Response
     */
    public function store(Reclist0Request $request)
    {
        $input    = $request->all();
        $reclist0 = $this->reclist0Repository->create($input);

        Flash::success(__('recommend.reclist0s.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('recommend.reclist0s.index'));

    }

    /**
     * Display the specified Reclist0.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $reclist0 = $this->reclist0Repository->findWithoutFail($id);

        if (empty($reclist0)) {
            Flash::error(__('recommend.reclist0s.not_found'));

            return redirect(route('recommend.reclist0s.index'));
        }

        return view('recommend.reclist0s.show')->with('reclist0', $reclist0);

    }

    /**
     * Show the form for editing the specified Reclist0.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        $reclist0 = $this->reclist0Repository->findWithoutFail($id);

        if (empty($reclist0)) {
            Flash::error(__('recommend.reclist0s.not_found'));

            return redirect(route('recommend.reclist0s.index'));
        }
        return Admin::content(function (Content $content) use ($id, $reclist0) {

            $content->header(__('recommend.reclist0s.edit_header'));
            $content->description(__('recommend.reclist0s.edit_description'));

            $content->body($this->form()->edit($id));

            $content->row(view('recommend.reclist0s.edit', ['reccat_id' => $reclist0->reccat_id, 'type_id' => $reclist0->type_id, 'range' => $reclist0->range, 'tpl_id' => $reclist0->tpl_id]));

        });
    }

    /**
     * Update the specified Reclist0 in storage.
     *
     * @param  int              $id
     * @param Reclist0Request $request
     *
     * @return Response
     */
    public function update($id, Reclist0Request $request)
    {
        $reclist0 = $this->reclist0Repository->findWithoutFail($id);

        if (empty($reclist0)) {
            Flash::error(__('recommend.reclist0s.not_found'));

            return redirect(route('recommend.reclist0s.index'));
        }
        $input = $request->all();

        $reclist0 = $this->reclist0Repository->update($input, $id);

        Flash::success(__('recommend.reclist0s.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('recommend.reclist0s.index'));
    }

    /**
     * Remove the specified Reclist0 from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->reclist0Repository->batchDelete('id', $id)) {

                return response()->json(['message' => __('recommend.reclist0s.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $reclist0 = $this->reclist0Repository->findWithoutFail($id);

        if (empty($reclist0)) {
            Flash::error(__('recommend.reclist0s.not_found'));

            return redirect(route('recommend.reclist0s.index'));
        }

        if ($flag = $this->reclist0Repository->delete($id)) {

            return response()->json(['message' => __('recommend.reclist0s.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(Reclist0::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('name', '推荐数据名称');
            $form->text('title', '显示名');
            $form->text('subtitle', '副标题');
            $reccats = Reccat::pluck('title', 'id');
            $form->select('reccat_id', '推荐类型')->options($reccats)->load('type_id', route('recommend.reclist0s.datas.reccats'), 'id', 'title');
            $form->select('type_id', '指定类型ID');
            $form->select('range', 'range')->options(array(
                0 => '选择',
                1 => 'area',
                2 => 'page',
                3 => 'app',
                4 => 'list',
            ))->load('tpl_id', route('entity.column.collists.tpls'), 'id', 'title');
            $paneltpls = Paneltpl::pluck('title', 'id')->toArray();
            $form->select('tpl_id', '模板')->options(array_merge(['0' => '选择'], $paneltpls));
            $form->text('bulk', '批次');
            // $form->number('count', '数据量');

            $form->display('created_at', __('base.created_at'));
            $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {
        return Admin::grid(Reclist0::class, function (Grid $grid) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // 添加按钮
            if (Admin::user()->cannot('recommend.reclist0s.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                $id = $actions->getKey();
                // 编辑按钮
                if (Admin::user()->cannot('recommend.reclist0s.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('recommend.reclist0s.destroy')) {
                    $actions->disableDelete();
                }

                $url = route('recommend.reclist0s.add_asset_data', ['reclist0_id' => $id, '_t' => rand(100000000, 900000000)]);
                $actions->append('<a href="' . $url . '" data-toggle="modal"  data-target="#add-reclist-model" title="数据添加">&nbsp;&nbsp;数据添加/&nbsp;&nbsp;</a>');

                $url = route('recommend.reclist0_datas.index', ['reclist0_id' => $id, '_t' => rand(100000000, 900000000)]);
                $actions->append('<a href="' . $url . '" title="数据编辑">&nbsp;&nbsp;数据编辑/&nbsp;&nbsp;</a>');
            });

            // 导出按钮
            if (Admin::user()->cannot('recommend.reclist0s.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('recommend.reclist0s.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('name', '推荐数据名称')->sortable();
            $grid->column('title', '显示名')->sortable();
            $grid->column('subtitle', '副标题')->sortable();
            $grid->column('reccat.title', '推荐类型')->sortable();

            $grid->column('type_id', '指定类型ID')->display(function ($value) {
                if (!empty($this->reccat)) {
                    $datasrcs = json_decode($this->reccat['datasrc'], true);
                    if (!empty($datasrcs)) {
                        foreach ($datasrcs as $key => $datasrc) {
                            if (is_array($datasrc) && !empty($datasrc)) {
                                // 获取数据中的表名
                                $tableName = $datasrc['table'];
                                // 如果数据库中有此表
                                if (Schema::hasTable($tableName)) {
                                    $name = DB::table($tableName)->where(['id' => $value])->value('title');
                                }
                            }
                        }
                    }
                }
                return empty($name) ? '' : $name;
            });
            $grid->column('range', 'range')->display(function ($val) {
                switch ($val) {
                    case '1':
                        return '<span class="badge bg-green">area</span>';
                        break;
                    case '2':
                        return '<span class="badge bg-green">page</span>';
                        break;
                    case '3':
                        return '<span class="badge bg-green">app</span>';
                        break;
                    case '4':
                        return '<span class="badge bg-green">list</span>';
                        break;
                    default:
                        return '';
                        break;
                }
            });
            $grid->column('tpl_id', '模板')->display(function ($val) {
                $returnName = '';
                switch ($this->range) {
                    case '1':
                        $returnName = Paneltpl::where(['id' => $val])->value('title');
                        break;
                    default:
                        $returnName = Pagetpl::where(['id' => $val])->value('title');
                        break;
                }
                return empty($returnName) ? '' : $returnName;
            });
            $grid->column('bulk', '批次')->sortable();
            $grid->column('count', '数据量')->display(function ($val) {
                return Reclist0Data::where(['reclist0_id' => $this->id])->count();
            });

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();
                $filter->like('name', '名称');

            });
        });
    }

    /**
     *  编辑栏目推荐数据
     * @param Request $request [description]
     */
    public function addReclistAssetData(Request $request)
    {
        $reclist0Iid = $request->input('reclist0_id');

        $reclist0 = $this->reclist0Repository->with('reccat')->findWithoutFail($reclist0Iid);
        if (empty($reclist0)) {
            Flash::error(__('recommend.reclist0s.not_found'));

            return redirect(route('recommend.reclist0s.index'));
        }
        $datas = [];
        $data  = [];
        // if (!empty($reclist0->reccat)) {
        //     $datasrcs = json_decode($reclist0->reccat->datasrc, true);
        //     foreach ($datasrcs as $key => $value) {
        //         $data[$key]['id']    = $value['type'];
        //         $data[$key]['title'] = $value['name'];
        //     }
        // }
        if (!empty($reclist0->reccat)) {
            switch ($reclist0->reccat->name) {
                // 栏目推荐
                case 'LMTJ':
                    // $data = [
                    //     ['id'=>'1','title'=>'视频'],
                    //     ['id'=>'2','title'=>'音频'],
                    //     ['id'=>'3','title'=>'图文'],
                    // ];
                    break;
                // 栏目列表推荐
                case 'LMLBTJ':
                    $muticolumnIds = CollistData::with(['columnType' => function ($query) {
                        $query->where(['name' => 'column']);
                    }])->where(['collist_id' => $reclist0->type_id])
                        ->pluck('data_id')
                        ->toArray();
                    $data = Muticolumn::whereIn('id', $muticolumnIds)->get(['title', 'id'])->toArray();
                    break;
                case 'QJTJ':
                    # code...
                    break;
                default:
                    # code...
                    break;
            }
        }
        // $data = array_merge([['id'=>'0','title'=>'选择']],$data);
        $datas['datas']       = $data;
        $datas['reclist0_id'] = $reclist0Iid;
        return view('recommend.reclist0s.create', $datas);
    }

    /**
     * 根据节目类型获取数据源
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function getDataByAssetType(Request $request)
    {
        // 搜索框的值
        $search_value = $request->input('search_value');
        // 媒资类型
        $assetType = $request->input('asset_type');
        // 栏目ID
        $reclist0Id = $request->input('reclist0_id');
        $reclist0   = Reclist0::with(['reccat', 'reclist0Data'])->where(['id' => $reclist0Id])->first();
        if (empty($reclist0)) {
            Flash::error(__('recommend.reclist0s.not_found'));
            return redirect(route('recommend.reclist0s.index'));
        }
        $relation             = [];
        $whereData            = [];
        $columnAssets         = [];
        $muticolumnId         = null;
        $data                 = [];
        $selectedVassetiId    = [];
        $selectedAassetiId    = [];
        $selectedTassetiId    = [];
        $selectedVassetiCount = 0;
        $selectedAassetiCount = 0;
        $selectedTassetiCount = 0;
        if (!empty($reclist0->reclist0Data->first())) {
            $reclist0Datas = $reclist0->reclist0Data->groupBy('data_type');
            // dd($reclist0Datas->toArray());
            $selectedVassetiId    = $reclist0Datas->get(1) ? $reclist0Datas->get(1)->pluck('data_id') : [];
            $selectedVassetiCount = count($selectedVassetiId);
            $selectedAassetiId    = $reclist0Datas->get(2) ? $reclist0Datas->get(2)->pluck('data_id') : [];
            $selectedAassetiCount = count($selectedAassetiId);
            $selectedTassetiId    = $reclist0Datas->get(3) ? $reclist0Datas->get(3)->pluck('data_id') : [];
            $selectedTassetiCount = count($selectedTassetiId);
        }
        $data['draw'] = $request->get('draw');
        $start        = $request->get('start') ?: 0;
        $length       = $request->get('length') ?: 10;
        $order        = $request->get('order');
        $columns      = $request->get('columns');
        $search       = $request->get('search');
        if ($order) {
            $orderColumData = $columns[$order[0]['column']]['data'];
        }
        $ord = '';
        if (!empty($orderColumData)) {
            $ord = $orderColumData . ' ' . $order[0]['dir'];
        } else {
            $ord = 'id asc';
        }
        $muticolumnAssetcount    = DB::table('column_assets')->where(['muticolumn_id' => $muticolumnId])->count();
        $count                   = intval($muticolumnAssetcount - ($selectedVassetiCount + $selectedAassetiCount + $selectedTassetiCount));
        $data['recordsTotal']    = $count;
        $data['recordsFiltered'] = $count;
        try {
            $selectedMerged = [];
            // 推荐数据定义的数据栏目类型来进行判断
            if (!empty($reclist0->reccat)) {
                $reccatName = $reclist0->reccat->name;
                if ($reccatName == 'LMTJ' || $reccatName == 'LMLBTJ') {
                    if ($reccatName == 'LMTJ') {
                        $muticolumnId = $reclist0->type_id;
                    }
                    if ($reccatName == 'LMLBTJ') {
                        $muticolumnId = $assetType;
                    }
                    //  媒资
                    $vassets = DB::table('column_assets as c')
                        ->select(['c.id', 'c.asset_type', 'v.name', 'v.title', 'v.subtitle'])
                        ->where(['c.asset_type' => 1, 'c.muticolumn_id' => $muticolumnId])
                        ->whereNotIn('c.asset_id', $selectedVassetiId)
                        ->whereNull('c.deleted_at')
                        ->leftJoin('vassetis as v', 'c.asset_id', '=', 'v.id')
                        ->get();
                    // 音频
                    $aassets = DB::table('column_assets as c')
                        ->select(['c.id', 'c.asset_type', 'v.name', 'v.title', 'v.subtitle'])
                        ->where(['c.asset_type' => 2, 'c.muticolumn_id' => $muticolumnId])
                        ->whereNotIn('c.asset_id', $selectedAassetiId)
                        ->whereNull('c.deleted_at')
                        ->leftJoin('vassetis as v', 'c.asset_id', '=', 'v.id')
                        ->get();
                    // 媒资音频合并
                    $merged = $vassets->merge($aassets);
                    // 图文
                    $tassets = DB::table('column_assets as c')
                        ->select(['c.id', 'c.asset_type', 'v.name', 'v.title', 'v.subtitle'])
                        ->where(['c.asset_type' => 3, 'c.muticolumn_id' => $muticolumnId])
                        ->whereNotIn('c.asset_id', $selectedTassetiId)
                        ->whereNull('c.deleted_at')
                        ->leftJoin('vassetis as v', 'c.asset_id', '=', 'v.id')
                        ->get();
                    $selectedMerged = $merged->merge($tassets);

                } elseif ($reccatName == 'QJTJ') {
                }

            }
            $data['data'] = $selectedMerged;
        } catch (Exception $e) {
            dd($e->getMessage());
        }

        return response()->json($data);
    }

    /**
     * 保存推荐数据
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function assetDataStore(Request $request)
    {
        // 获取传递过来是哪个栏目
        $reclist0Id = $request->input('reclist0_id');
        if (empty($reclist0Id)) {
            return response()->json(['content' => '推荐数据ID不能为空', 'status' => false]);
        }

        // 获取所有传递来的数据ID
        $dataId = $request->input('data_id');
        if (!is_array($dataId)) {
            return response()->json(['content' => '数据为空,请选择数据', 'status' => false]);
        }
        $datas = [];
        DB::beginTransaction();
        try {
            foreach ($dataId as $key => $value) {
                $columnAsset = ColumnAsset::where(['id' => $value])->first();
                if (!empty($columnAsset)) {
                    $reclist0Data = Reclist0Data::where(['reclist0_id' => $reclist0Id, 'data_type' => $columnAsset->asset_type, 'data_id' => $columnAsset->asset_id])->first();
                    if (empty($reclist0Data)) {
                        switch ($columnAsset->asset_type) {
                            case '1':
                                $result = Vasseti::where(['id' => $columnAsset->asset_id])->first();
                                break;
                            case '2':
                                $result = Vasseti::where(['id' => $columnAsset->asset_id])->first();
                                break;
                            case '3':
                                $result = Vasseti::where(['id' => $columnAsset->asset_id])->first();
                                break;
                            default:
                                $result = Vasseti::where(['id' => $columnAsset->asset_id])->first();
                                break;
                        }
                        if (!empty($result)) {
                            $datas[$key]['title']       = $result->title;
                            $datas[$key]['subtitle']    = $result->subtitle;
                            $datas[$key]['bulk']        = 0;
                            $datas[$key]['reclist0_id'] = $reclist0Id;
                            $datas[$key]['data_type']   = $columnAsset->asset_type;
                            $datas[$key]['data_id']     = $columnAsset->asset_id;
                            $datas[$key]['range']       = 0;
                            $datas[$key]['tpl_id']      = 0;
                            $datas[$key]['img']         = null;
                            $datas[$key]['created_at']  = date('Y-m-d H:i:s');
                        }
                    }
                }
            }
            // dd($datas);
            DB::table('reclist0_datas')->insert($datas);
            DB::commit();
            return response()->json(['content' => '添加成功！', 'status' => true]);
        } catch (Exception $e) {
            DB::rollback();
            return response()->json(['content' => '添加失败！', 'status' => false]);
        }
    }

    /**
     * 获取数据根据推荐数据定义
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function getDataByReccatId(Request $request)
    {
        $recacatId  = $request->get('q');
        $returnData = [];
        $reccat     = Reccat::where(['id' => $recacatId])->first();
        if (!empty($reccat)) {
            // 获取推荐数据类型中定义的表名称
            $datasrcs = json_decode($reccat->datasrc, true);
            if (!empty($datasrcs)) {
                foreach ($datasrcs as $key => $datasrc) {
                    // 获取表名称
                    $tableName = $this->getTableNameByDatasrc($datasrc);
                    if (!empty($tableName)) {
                        $returnData = DB::table($tableName)->orderBy('listorder', 'asc')->get(['title', 'id'])->toArray();
                    }
                }
            }
        }
        return array_merge([['id' => '0', 'title' => '选择']], $returnData);
    }
    /**
     * ajax获取数据根据推荐数据定义
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function getResourceDataByReccatId($reccatId, Request $request)
    {
        $datas  = [];
        $reccat = Reccat::where(['id' => $reccatId])->first();
        if (!empty($reccat)) {
            // 获取推荐数据类型中定义的表名称
            $datasrcs = json_decode($reccat->datasrc, true);
            foreach ($datasrcs as $key => $datasrc) {
                // 获取表名称
                $tableName = $this->getTableNameByDatasrc($datasrc);
                if (!empty($tableName)) {
                    $datas = DB::table($tableName)->orderBy('listorder', 'asc')->get(['title', 'id'])->toArray();
                }
            }
        }
        return response()->json(['content' => array_merge([['id' => '0', 'title' => '选择']], $datas), 'status' => true]);
    }

    /**
     * 根据数据源获取表名
     * @param  [type] $datasrc [description]
     * @return [type]          [description]
     */
    public function getTableNameByDatasrc($datasrc = [])
    {
        $tableName = null;
        if (is_array($datasrc) && !empty($datasrc)) {
            // 获取数据中的表名
            $tableName = $datasrc['table'];
            // 如果数据库中有此表
            if (Schema::hasTable($tableName)) {
                return $tableName;
            }
        }
        return $tableName;
    }
}
